package com.supreme.studyserver.aspect;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Aspect
@Component
public class DataScopeAspect {

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Pointcut(value = "@annotation(com.supreme.studyserver.annotation.DataScope)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) throws IllegalAccessException {
        //1.获取namespace+methdoName
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String namespace = method.getDeclaringClass().getName();
        String methodName = method.getName();

        //2.根据namespace+methdoName获取相对应的MappedStatement
        Configuration configuration = sqlSessionFactory.getConfiguration();
        MappedStatement mappedStatement = configuration.getMappedStatement(namespace+"."+methodName);

        // 获得 private final SqlSource sqlSource; 对象
        Field sqlSource = FieldUtils.getField(mappedStatement.getClass(), "sqlSource", true);
        sqlSource.setAccessible(true);
        // 动态数据源
        DynamicSqlSource staticSqlSource = (DynamicSqlSource) sqlSource.get(mappedStatement);

        System.out.println("doBefore");
    }
}
